import { getSbData, supabase, supaTabs } from "../base/supabase";

export async function onBaseUpsert(table, params) {
  const body = {};
  for (const key in params) {
    if (/^_/.test(key) || key == "id") {
      continue;
    }
    body[key] = params[key];
  }
  let res = supabase.from(table);
  let act = "insert";
  if (!params.id) {
    res = await res
      .insert([body])
      .select()
      .order("id", {
        ascending: false,
      })
      .limit(1);
  } else {
    if (params._delete) {
      act = "delete";
      res = res.delete();
      // 物理删除，误删可以通过log恢复
    } else {
      act = "update";
      res = res.update(body);
    }
    res = await res.eq("id", params.id).select();
  }
  const list = getSbData(res);
  const item = list[0]; // 只有act=delete但记录已删除时，item为空
  if (item) {
    onLog({
      tab_name: table,
      act,
      rel_id: params.id,
      body: act == "delete" ? item : body, // 删除时存被删的完整记录，新增修改时仅存变化数据
    });
  }
  return {
    item,
  };
}

async function onLog(params) {
  const { act, body } = params;
  if (act == "delete") {
    for (const key in body) {
      if (body[key] === null) delete body[key];
    }
  }
  await supabase.from(supaTabs.SysLog).insert([params]);
}
